package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
 * Servlet implementation class Test
 */
public class Test extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Test() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String appid = "00001368";
		String keytext = "";
		String hiddenkey = "AibgZsBJdV";
		URL getKeyUrl = new URL("http://api.traffy.in.th/apis/getKey.php?appid=" + appid);
		URLConnection getKeyCon = getKeyUrl.openConnection();
        BufferedReader key = new BufferedReader(new InputStreamReader(getKeyCon.getInputStream()));
        
		keytext = key.readLine();
		String passkey="";
		try {
			passkey = encodeString(appid+keytext.trim()) + encodeString(hiddenkey+keytext.trim());
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
//		URL getLinkUrl = new URL("http://athena.traffy.in.th/apis/apitraffy.php?api=getLinkInfo&key="+passkey+"&appid=00001368&format=xml&source=trafficpolice&radius=13.75055703,100.52318573,1000");
//		URL getLinkUrl = new URL("http://api.traffy.in.th/apis/apitraffy.php?format=XML&api=getCL&key="+passkey+"&appid=00001368&linkid=3177,12477,17153,747,10736,12613,8098,3177,1389,15825,17153,12477,747,15186,1506,4670,12613,8119,5990,16450,8098,3177,1389,15825,17153,12477,747,15186,1506,4670,12613,8119,5990,16450,11323,3901,4800,1746,4035,4778,14463,7161,7426,4795,11945,12585,689,9417,10846,10037,4016,11368,12794,3728,9676,12236,3802,4652,2142,2702,5339,5870,7467,11447,1960,3592,3953");
		URL getLinkUrl = new URL("http://athena.traffy.in.th/apis/apitraffy.php?api=getRainForecast&key="+passkey+"&appid=00001368&format=XML&location=14.077869,100.601099&type=1&pt=10");
		URLConnection getLinkCon = getLinkUrl.openConnection();
        BufferedReader linkXML = new BufferedReader(new InputStreamReader(getLinkCon.getInputStream()));
        String inputLine;

        while ((inputLine = linkXML.readLine()) != null){
        		System.out.println(inputLine);
        }
        linkXML.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	
	public String encodeString(String txt) throws NoSuchAlgorithmException, UnsupportedEncodingException  { 
    	// Use MD5
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");
        byte[] md5hash = new byte[32];
        md.update(txt.getBytes("iso-8859-1"), 0, txt.length());
        md5hash = md.digest();
        return convertToHex(md5hash);
    } 
    
    private static String convertToHex(byte[] data) { 
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < data.length; i++) { 
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do { 
                if ((0 <= halfbyte) && (halfbyte <= 9)) 
                    buf.append((char) ('0' + halfbyte));
                else 
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while(two_halfs++ < 1);
        } 
        return buf.toString();
    } 
    
    public String parseLinkInfoXML(String linkXML) throws SAXException, IOException, ParserConfigurationException{
    	String linkId = "";
    	if(!linkXML.equals("Information Not Available")){
	    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	        DocumentBuilder db = dbf.newDocumentBuilder();
	        InputSource is = new InputSource();
	        is.setCharacterStream(new StringReader(linkXML));
	
	        Document doc = db.parse(is);
	        NodeList nodes = doc.getElementsByTagName("linkinfo");
	
	        // Get only one linkId
	        for (int i = 0; i < nodes.getLength(); i++) {
	           Element element = (Element) nodes.item(i);
	
	           linkId += ","+element.getAttribute("linkid");
	        }
	    }else{
	    	linkId = "0";
	    }
    	
    	return linkId;
    }
}


